# polls/views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect, JsonResponse
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from django.contrib import messages
from django.db.models import Count

from .models import Question, Choice

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'
    
    def get_queryset(self):
        """返回最近发布的5个活跃问题"""
        return Question.objects.filter(
            pub_date__lte=timezone.now(),
            is_active=True
        ).annotate(
            num_choices=Count('choice')
        ).filter(
            num_choices__gte=2
        ).order_by('-pub_date')[:5]
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['active_polls'] = Question.objects.filter(
            pub_date__lte=timezone.now(),
            end_date__gte=timezone.now(),
            is_active=True
        ).count()
        context['total_polls'] = Question.objects.count()
        return context

class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'
    
    def get_queryset(self):
        """排除未发布或已结束的问题"""
        now = timezone.now()
        return Question.objects.filter(
            pub_date__lte=now,
            is_active=True
        )
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        question = self.object
        context['time_remaining'] = question.days_remaining
        return context

class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'
    
    def get_queryset(self):
        """排除未发布的问题"""
        return Question.objects.filter(
            pub_date__lte=timezone.now(),
            is_active=True
        )

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    if not question.is_currently_active():
        messages.error(request, "该投票已结束，无法继续投票")
        return redirect('polls:index')
    
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        messages.error(request, "您没有选择任何选项")
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "您没有选择任何选项",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        messages.success(request, "投票成功！")
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

def get_results_data(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    choices = question.choice_set.all()
    
    data = {
        'labels': [choice.choice_text for choice in choices],
        'data': [choice.votes for choice in choices],
        'percentages': [choice.percentage for choice in choices],
        'colors': ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b', '#858796']
    }
    return JsonResponse(data)